<template>
  <view class="container">
    <!-- 书籍详情内容 -->
    <view v-if="book" class="book-detail">
      <!-- 书籍封面和基本信息 -->
      <view class="book-header">
        <view class="book-cover-section">
          <image 
            class="book-cover" 
            :src="book.coverUrl || '/static/images/default-book.png'" 
            mode="aspectFill"
            @error="handleImageError"
          />
        </view>
        <view class="book-basic-info">
          <text class="book-title">{{ book.bookName }}</text>
          <text class="book-author">作者：{{ book.author }}</text>
          <view class="book-rating">
            <text class="rating-label">评分：</text>
            <text class="rating-score">{{ book.score }}</text>
            <text class="rating-stars">{{ getStarRating(book.score) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 书籍元数据 -->
      <view class="book-meta">
        <view class="meta-item">
          <text class="meta-label">类型：</text>
          <text class="meta-value book-type">{{ book.bookType }}</text>
        </view>
        <view class="meta-item" v-if="book.publisher">
          <text class="meta-label">出版社：</text>
          <text class="meta-value">{{ book.publisher }}</text>
        </view>
        <view class="meta-item" v-if="book.isbn">
          <text class="meta-label">ISBN：</text>
          <text class="meta-value">{{ book.isbn }}</text>
        </view>
      </view>
      
      <!-- 内容简介 -->
      <view class="book-intro">
        <text class="intro-title">内容简介</text>
        <text class="intro-content">{{ book.introduction || '暂无简介' }}</text>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button class="btn btn-primary" @click="addToFavorites">
          <text class="btn-text">{{ isFavorite ? '已收藏' : '收藏' }}</text>
        </button>
        <button class="btn btn-secondary" @click="shareBook">
          <text class="btn-text">分享</text>
        </button>
      </view>
    </view>
    
    <!-- 错误状态 -->
    <view v-else-if="error" class="error-state">
      <view class="error-icon">⚠️</view>
      <text class="error-message">{{ error }}</text>
      <button class="retry-btn" @click="fetchBookDetail">
        <text class="retry-text">重新加载</text>
      </button>
    </view>
    
    <!-- 加载状态 -->
    <view v-else class="loading-state">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 响应式数据
const book = ref(null)
const bookId = ref(null)
const error = ref(null)
const loading = ref(false)
const isFavorite = ref(false)

// API配置
const API_BASE_URL = 'http://192.168.153.1:8080'

// 获取书籍详情
const fetchBookDetail = async () => {
  if (!bookId.value) {
    error.value = '缺少书籍ID参数'
    return
  }

  loading.value = true
  error.value = null
  
  uni.showLoading({
    title: '加载中...'
  })
  
  try {
    const response = await new Promise((resolve, reject) => {
      uni.request({
        url: `${API_BASE_URL}/books/selectBookByBookId`,
        method: 'POST',
        data: {
          bookId: bookId.value
        },
        header: {
          'Content-Type': 'application/json'
        },
        timeout: 10000,
        success: (res) => {
          console.log('书籍详情API响应:', res)
          resolve(res)
        },
        fail: (err) => {
          console.error('请求失败:', err)
          reject(err)
        }
      })
    })
    
    if (response.statusCode === 200) {
      const resData = response.data
      
      if (resData.code === 200200 && resData.data && resData.data.book) {
        // 处理API响应数据
        const bookData = resData.data.book[0] // API返回的是数组，取第一个元素
        
        if (bookData) {
          // 映射API字段到组件使用的字段
          book.value = {
            id: bookData.book_id,
            bookName: bookData.book_name,
            author: bookData.author,
            score: bookData.score,
            bookType: bookData.book_type,
            publisher: bookData.publisher,
            isbn: bookData.isbn,
            introduction: bookData.introduction,
            coverUrl: bookData.cover_url || bookData.cover || '' // 如果有封面URL字段
          }
          
          console.log('处理后的书籍数据:', book.value)
          
          // 记录浏览历史
          recordViewHistory()
          
          // 检查是否已收藏
          checkFavoriteStatus()
        } else {
          error.value = '书籍数据为空'
        }
      } else {
        error.value = resData.message || '获取书籍详情失败'
      }
    } else {
      error.value = `请求失败: HTTP ${response.statusCode}`
    }
  } catch (err) {
    console.error('获取书籍详情异常:', err)
    error.value = '网络错误，请检查网络连接'
  } finally {
    loading.value = false
    uni.hideLoading()
    
    if (error.value) {
      uni.showToast({
        title: error.value,
        icon: 'none',
        duration: 3000
      })
    }
  }
}

// 记录浏览历史
const recordViewHistory = async () => {
  const user = uni.getStorageSync('userInfo')
  if (!user?.U_Id) {
    console.log('未登录用户，不记录浏览历史')
    return
  }
  
  console.log('记录浏览历史，用户ID:', user.U_Id, '书籍ID:', bookId.value)
  
  try {
    const response = await new Promise((resolve, reject) => {
      uni.request({
        url: `${API_BASE_URL}/history/insert`,
        method: 'POST',
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: `userId=${user.U_Id}&bookId=${bookId.value}`,
        success: resolve,
        fail: reject
      })
    })
    
    if (response.statusCode === 200) {
      console.log('浏览历史记录成功')
    } else {
      console.error('记录浏览历史失败:', response.data)
    }
  } catch (err) {
    console.error('记录浏览历史异常:', err)
  }
}

// 检查收藏状态
const checkFavoriteStatus = async () => {
  const user = uni.getStorageSync('userInfo')
  if (!user?.U_Id) return
  
  try {
    const response = await new Promise((resolve, reject) => {
      uni.request({
        url: `${API_BASE_URL}/favorites/check`,
        method: 'POST',
        data: {
          userId: user.U_Id,
          bookId: bookId.value
        },
        success: resolve,
        fail: reject
      })
    })
    
    if (response.statusCode === 200 && response.data.code === 200200) {
      isFavorite.value = response.data.data.isFavorite || false
    }
  } catch (err) {
    console.error('检查收藏状态失败:', err)
  }
}

// 添加/取消收藏
const addToFavorites = async () => {
  const user = uni.getStorageSync('userInfo')
  if (!user?.U_Id) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }
  
  try {
    const action = isFavorite.value ? 'remove' : 'add'
    const response = await new Promise((resolve, reject) => {
      uni.request({
        url: `${API_BASE_URL}/favorites/${action}`,
        method: 'POST',
        data: {
          userId: user.U_Id,
          bookId: bookId.value
        },
        success: resolve,
        fail: reject
      })
    })
    
    if (response.statusCode === 200 && response.data.code === 200200) {
      isFavorite.value = !isFavorite.value
      uni.showToast({
        title: isFavorite.value ? '收藏成功' : '取消收藏',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: '操作失败',
        icon: 'none'
      })
    }
  } catch (err) {
    console.error('收藏操作失败:', err)
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

// 分享书籍
const shareBook = () => {
  if (!book.value) return
  
  uni.showActionSheet({
    itemList: ['分享给朋友', '复制链接'],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 分享给朋友的逻辑
        uni.showToast({
          title: '分享功能开发中',
          icon: 'none'
        })
      } else if (res.tapIndex === 1) {
        // 复制链接的逻辑
        uni.setClipboardData({
          data: `推荐一本好书：《${book.value.bookName}》 - ${book.value.author}`,
          success: () => {
            uni.showToast({
              title: '已复制到剪贴板',
              icon: 'success'
            })
          }
        })
      }
    }
  })
}

// 获取星级评分显示
const getStarRating = (score) => {
  const numScore = parseFloat(score) || 0
  const fullStars = Math.floor(numScore / 2)
  const hasHalfStar = (numScore % 2) >= 1
  
  let stars = '★'.repeat(fullStars)
  if (hasHalfStar) stars += '☆'
  stars += '☆'.repeat(5 - fullStars - (hasHalfStar ? 1 : 0))
  
  return stars
}

// 处理图片加载错误
const handleImageError = (e) => {
  console.log('书籍封面加载失败:', e)
}

// 页面生命周期
onLoad((options) => {
  console.log('页面加载参数:', options)
  
  if (!options.id) {
    error.value = '缺少书籍ID参数'
    uni.showToast({
      title: '参数错误',
      icon: 'none',
      complete: () => {
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    })
    return
  }
  
  bookId.value = options.id
  fetchBookDetail()
})

onMounted(() => {
  console.log('组件挂载完成')
})
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 20rpx;
}

.book-detail {
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.book-header {
  display: flex;
  padding: 40rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.book-cover-section {
  margin-right: 30rpx;
}

.book-cover {
  width: 200rpx;
  height: 280rpx;
  border-radius: 12rpx;
  background-color: rgba(255, 255, 255, 0.1);
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.2);
}

.book-basic-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.book-title {
  font-size: 44rpx;
  font-weight: bold;
  line-height: 1.3;
  margin-bottom: 20rpx;
  color: white;
}

.book-author {
  font-size: 32rpx;
  margin-bottom: 20rpx;
  opacity: 0.9;
}

.book-rating {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.rating-label {
  font-size: 28rpx;
  margin-right: 10rpx;
}

.rating-score {
  font-size: 36rpx;
  font-weight: bold;
  color: #ffd700;
  margin-right: 15rpx;
}

.rating-stars {
  font-size: 24rpx;
  color: #ffd700;
}

.book-meta {
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.meta-label {
  font-size: 28rpx;
  color: #666;
  min-width: 120rpx;
}

.meta-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.book-type {
  background: #e3f2fd;
  color: #1976d2;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.book-intro {
  padding: 40rpx;
}

.intro-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  display: block;
}

.intro-content {
  font-size: 30rpx;
  line-height: 1.8;
  color: #555;
  text-align: justify;
}

.action-buttons {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx 40rpx;
}

.btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-secondary {
  background: #f8f9fa;
  color: #666;
  border: 2rpx solid #e9ecef;
}

.btn:active {
  transform: scale(0.98);
}

.btn-text {
  font-size: 32rpx;
  font-weight: 500;
}

.loading-state, .error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.error-icon {
  font-size: 80rpx;
  margin-bottom: 30rpx;
}

.error-message {
  font-size: 28rpx;
  color: #e74c3c;
  margin-bottom: 40rpx;
  text-align: center;
}

.retry-btn {
  background: #667eea;
  color: white;
  padding: 20rpx 40rpx;
  border-radius: 40rpx;
  border: none;
  font-size: 28rpx;
}

.retry-text {
  color: white;
}
</style>